import React, { Component } from 'react'
import echarts from '@/lib/echarts'
import { connect } from 'react-redux'
import { debounce } from '@/utils'

class PieChart extends Component {

    static defaultProps = {
        width: '100%',
        height: '350px',
        styles: {},
        className: ''
    }
    state = {
        chart: null
    }

    componentDidMount() {
        window.addEventListener('resize', () => {
            this.resize()
        })
        this.initChart()
    }
    componentWillReceiveProps(nextProps) {
        // 监听菜单变化
        if (nextProps.sidebarCollapsed !== this.props.sidebarCollapsed) {
            setTimeout(() => {
                this.resize()
            }, 300)
        }
        if (nextProps.chartData !== this.props.chartData) {
            debounce(this.initChart().bind(this), 300)()
        }
    }
    // 组件销毁
    componentWillUnmount() {
        if (!this.state.chart) {
            return
        }
        this.setState({ chart: null })
    }
    // 重置chart
    resize() {
        if (this.state.chart) {
            debounce(this.state.chart.resize.bind(this), 300)()
        }
    }
    // 初始化chart
    initChart() {
        if (!this.el) {
            return
        }
        this.setState({ chart: echarts.init(this.el, 'macarons') }, () => {
            this.setOptions(this.props.chartData)
        })
    }
    setOptions(data) {
        this.state.chart.setOption({
            legend: {
                left: 'center',
                bottom: 10,
                data: ['净化器', '过滤器', '空气清新机']
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/> {b} : {c} ({d}%)"
            },
            series: [
                {
                    name: '商品分布',
                    type: 'pie',
                    roseType: 'radius',
                    radius: [15, 95],
                    center: ['50%', '38%'],
                    data
                }
            ]
        })
    }
    render() {
        const { width, height, styles, className } = this.props
        return (
            <div className={className}
                ref={el => (this.el = el)}
                style={{
                    ...styles,
                    width,
                    height
                }}
            ></div>
        )
    }
}
export default connect(state => state.app)(PieChart) 